<template>
  <div>
    <el-card>
      <el-form :model="form" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6" v-if="isShow == false">
            <el-form-item label="机构" prop="BRANCHNO">
              <select-tree :branch="form.branch.BRANCHNAME" @getBranchName="getBranch">
              </select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="排班计划编号" prop="SPID">
              <el-select v-model="form.SPID" placeholder="请选择排班计划" clearable>
                <el-option v-for="(item,index) in tableDataPlan" :key="index" :label="item.SPNAME" :value="item.SPID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6" v-if="isShow == false">
            <el-form-item label="坐席列表" prop="AGENTIDLISTSTR">
              <el-select v-model="form.AGENTIDLISTSTR" filterable placeholder="请选择坐席列表" multiple collapse-tags>
                <el-option v-for="item in tableDataUsers" :key="item.AGENTID" :label="item.AGENTNAME"
                  :value="item.AGENTID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker size="mini" style="width:100%;" v-model="form.startDate" type="date"
                value-format="yyyyMMdd" :clearable='false' placeholder="开始日期" :picker-options="pickerOptionsStart"
                @change="changeStart">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker style="width:100%;" size="mini" v-model="form.endDate" type="date" value-format="yyyyMMdd"
                placeholder="结束日期" :picker-options="pickerOptionsEnd" @change="changeEnd" :clearable='false'>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg='24' :md='12' style="margin-top:8px;">
            <el-button type="primary" icon="el-icon-search" size='mini' @click="queryClass('1')">查询
            </el-button>
          <!-- </el-col>
          <el-col :lg="2" :md="3" class="searchBtnMarginTop"> -->
            <el-button type="warning" size="mini" icon="el-icon-refresh" @click="resetForm('form')">重置</el-button>
          <!-- </el-col>
        </el-row>
        <el-row style="margin-bottom: 20px;">
         
          <el-col :lg="2" :md="3"> -->
            <el-button type="success" size="mini" icon="el-icon-download" @click="downloadTemplate">导出班表</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="margin-top:20px;">
            <el-table :data="tableData" :span-method="objectSpanMethod" border>
              <el-table-column prop="AGENTID" width="140" label="坐席编号" align="center"></el-table-column>
              <el-table-column prop="AGENTNAME"  width="140" label="坐席名称" align="center"></el-table-column>
              <el-table-column label="时间" align="center" width="160">
                <template slot-scope="scope">
                  <span>{{scope.row.CLASSESDATE | formFormat}}</span>
                </template>
              </el-table-column>
              <el-table-column label="事件" align="center">
                <template slot-scope="scope">
                  <div>
                    <p style="margin:0">
                      <el-tag :color="scope.row.CALCOLOUR" style="color:#696062;border-color:#fff;">
                        {{scope.row.ACTIVITYNAME}} </el-tag>
                      {{scope.row.SRTTIME}}-{{scope.row.ENDTIME}}
                      <el-tag type="success" size="mini">{{scope.row.SKILLFLG}}</el-tag>
                    </p>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-pagination style="text-align: right; margin-top:20px;" :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize" @size-change="handleInSizeChange" @current-change="handleInCurrentChange"
              :current-page="currpage" background layout="sizes, total, prev, pager, next, jumper" :total="tableTotal">
            </el-pagination>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>
<script>
  import branchQuery from '@/message/wfm/baseData/branchManage/branchQuery';
  import request from "@/common/utils/requestWFM";
  import formalClass from '@/message/wfm/userScheduleManage/formalClass/formalClassQuery';
  import queryPlanMaintain from '@/message/wfm/intelligenceSchedule/planMaintain/queryPlanMaintain';
  import userQuery from '@/message/wfm/baseData/userManage/userQuery';
  import selectTree from "@/components/selectTree5/";
  import toolBox from "@/common/utils/toolBox";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import download from '@/message/wfm/public/classImport'

  export default {
    props: {
      isShow: {
        type: Boolean,
        default: false
      },
      agentId: {
        type: Array,
        default: function () {
          return []
        }
      }
    },
    components: {
      selectTree
    },
    filters: {
      formFormat(val) {
        return toolBox.timeFormat2Date(val);
      }
    },
    data() {
      return {
        pickerOptionsStart: {
          disabledDate: (time) => {
            // return time.getTime() < Date.now()
          }
        },
        pickerOptionsEnd: {
          disabledDate: (time) => {
            // return time.getTime() < Date.now()
          }
        },
        tableData: [],
        form: { //表单数据
          startDate: '',
          endDate: '',
          branch: {
            BRANCHNO: this.$store.getters.BranchNum,
            BRANCHNAME: this.$store.getters.BranchName
          },
          SPID: '',
          AGENTIDLISTSTR: this.agentId,
        },
        spanArr: [],
        spanArr1: [],
        tableDataPlan: [], //排班计划数据
        tableDataUsers: [], //坐席数据
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        fileUrl: getGlobalParams.get("FileDownloadAddress"),
      }
    },
    created() {
      this.form.startDate = toolBox.getCurrentMonthFirstDay();
      this.changeStart();
      this.form.endDate = toolBox.getCurrentMonthLastDay();
      this.changeEnd();
    },
    mounted() {
      // 正式班表查询
      this.queryClass();
      // 查询排班计划
      this.queryPlanMaintain();
      // 查询坐席列表
      this.queryUser();
    },
    methods: {
      //在数组对象中去掉重复的对象:
      deteleObject(obj) {
        var uniques = [];
        var stringify = {};
        for (var i = 0; i < obj.length; i++) {
          var keys = Object.keys(obj[i]);
          keys.sort(function (a, b) {
            return (Number(a) - Number(b));
          });
          var str = '';
          for (var j = 0; j < keys.length; j++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
          }
          if (!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str] = true;
          }
        }
        uniques = uniques;
        return uniques;
      },
      // 导出班表
      async downloadTemplate() {
        let resBody = new download()
        resBody.data.BRANCHNO = this.form.branch.BRANCHNO
        resBody.data.SPID = this.form.SPID
        resBody.data.QUREYSRTDATE = this.form.startDate
        resBody.data.QUREYENDDATE = this.form.endDate
        resBody.data.AGENTIDLISTSTR = this.form.AGENTIDLISTSTR.join(',');
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          let res = response.BODY
          let name = res.FileName
          let url = res.FilePath
          this.downloadFile(this.fileUrl + url + '/' + name)
          //  console.log(response)
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        this.queryClass();
      },
      handleInSizeChange(val) {
        this.pageSize = val;
        this.queryClass();
      },
      // 获取本月第一天和最后一天
      // getCurrentMonthFirstDay() {
      //   var date = new Date()
      //   date.setDate(1)
      //   var month = parseInt(date.getMonth() + 1)
      //   var day = date.getDate()
      //   if (month < 10) {
      //     month = '0' + month
      //   }
      //   if (day < 10) {
      //     day = '0' + day
      //   }
      //   return date.getFullYear() + '' + month + '' + day
      // },
      // getCurrentMonthLastDay() {
      //   var date = new Date()
      //   var year = date.getFullYear()
      //   var month = date.getMonth() + 1
      //   month = month < 10 ? '0' + month : month
      //   var day = new Date(year, month, 0)
      //   return  year + '' + month + '' + day.getDate()
      // },
      //表格单元格合并
      objectSpanMethod({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
          if (this.spanArr[rowIndex] && columnIndex != 2) {
            return {
              rowspan: this.spanArr[rowIndex],
              colspan: 1
            }
          } else if (this.spanArr1[rowIndex] && columnIndex === 2) {
            return {
              rowspan: this.spanArr1[rowIndex],
              colspan: 1
            }
          } else {
            return {
              rowspan: 0,
              colspan: 0
            }
          }
        }
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      changeStart() {
        this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
          disabledDate: (time) => {
            if (this.form.startDate) {
              return time.getTime() < Date.parse(this.form.startDate.slice(0, 4) + '-' + this.form
                .startDate.slice(4, 6) +
                '-' + this.form.startDate.slice(6, 8)) - 8.64e7
            } else {
              return time.getTime() < Date.now();
            }
          }
        })
      },
      changeEnd() {
        this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
          disabledDate: (time) => {
            if (this.form.endDate) {
              return time.getTime() > Date.parse(this.form.endDate.slice(0, 4) + '-' + this.form.endDate
                .slice(4, 6) + '-' +
                this.form.endDate.slice(6, 8))
            } else {
              // return time.getTime() < Date.now();
            }
          }
        })
      },
      getBranch(data) {
        // 机构变化相对应查询机构下的坐席和排班计划
        this.form.branch.BRANCHNO = data.BRANCHNO;
        this.form.branch.BRANCHNAME = data.BRANCHNAME;
        this.form.SPID = '';
        this.queryPlanMaintain();
        this.queryUser();
      },
      // 查询班表
      async queryClass(data) {
        if (data) {
          this.currpage = 1;
        }
        let resBody = new formalClass()
        resBody.data.BRANCHNO = this.form.branch.BRANCHNO
        resBody.data.SPID = this.form.SPID
        resBody.data.QUREYSRTDATE = this.form.startDate
        resBody.data.QUREYENDDATE = this.form.endDate
        resBody.data.AGENTIDLISTSTR = this.form.AGENTIDLISTSTR.join(',');
        resBody.data.CurrPage = this.currpage;
        resBody.data.PageRowNum = this.pageSize + '';;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.tableData = response.BODY.AGENTINFO;
          this.tableTotal = response.BODY.TotalRowNum;
          var table = [];
          this.tableData.forEach(item => {
            // 排序
            item.SCHEDULELIST.sort(this.compare('CLASSESDATE'));
            item.SCHEDULELIST.forEach(info => {
              if (info.ACTIVITYNAME) {
                table.push({
                  'AGENTID': item.AGENTID,
                  'AGENTNAME': item.AGENTNAME,
                  'ACTIVITYNAME': info.ACTIVITYNAME,
                  'CALCOLOUR': info.CALCOLOUR,
                  'SRTTIME': info.SRTTIME,
                  'ENDTIME': info.ENDTIME,
                  'CLASSESDATE': info.CLASSESDATE,
                  'SKILLFLG': info.SKILLFLG,
                })
              }
            })
          })
          this.tableData = table;
          let contactDot = 0;
          let contactDot1 = 0;
          this.spanArr = [];
          this.spanArr1 = [];
          table.forEach((info, index) => {
            if (index - 1 >= 0 && info.AGENTID === table[index - 1].AGENTID) {
              this.spanArr[contactDot] += 1;
              this.spanArr.push(0)
            } else {
              contactDot = index
              this.spanArr.push(1)
            }
            if (index - 1 >= 0 && info.CLASSESDATE === table[index - 1].CLASSESDATE && info.AGENTID == table[
                index - 1].AGENTID) {
              this.spanArr1[contactDot1] += 1;
              this.spanArr1.push(0)
            } else {
              contactDot1 = index
              this.spanArr1.push(1)
            }
          })
          let arr1 = []
          this.tableData.forEach(item=>{
            arr1.push({
              'AGENTID':item.AGENTID,
              'AGENTNAME':item.AGENTNAME,
              'CLASSESDATE':item.CLASSESDATE,
            })
          })
          // console.log(this.spanArr);
          // console.log(this.spanArr1);
          // let arr2 = this.deteleObject(arr1)
          // this.tableData.forEach(item => {
          //   arr2.forEach(ele => {
          //     if(item.AGENTID == ele.AGENTID && item.CLASSESDATE == ele.CLASSESDATE){

          //     }
          //   })
          // })
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 查询排班计划
      async queryPlanMaintain() {
        let resBody = new queryPlanMaintain();
        resBody.data.BRANCHNO = this.form.branch.BRANCHNO;
        resBody.data.SPNAME = '';
        resBody.data.SRTDATE = '';
        resBody.data.SPID = '';
        resBody.data.CurrPage = '1';
        resBody.data.PageRowNum = '100' || this.pageSize;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          // 查询出数据
          this.tableDataPlan = toolBox.removal(response.BODY.RSPSTRUCT,'SPID');
          // this.tableTotal = response.BODY.TotalRowNum;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
      },
      queryUser() { //查询用户表格
        let resBody = new userQuery();
        resBody.data.AGENTID = '';
        resBody.data.AGENTNAME = '';
        resBody.data.BRANCHNO = this.form.branch.BRANCHNO;
        resBody.data.CurrPage = '1' || this.currentPageUser;
        resBody.data.PageRowNum = '100' || this.pageSize;
        request(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.tableDataUsers = response.BODY.AGENTDATA;
            } else {
              this.$message({
                type: "error",
                message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
              })
            }
          })
          .catch(error => {
            this.loading = false;
          });
      },
      // 根据字段排序
      compare(key) {
        return function (value1, value2) {
          var val1 = value1[key];
          var val2 = value2[key];
          return val1 - val2;
        }
      },
      removeSame1(list) {
        let keys = [],
          item;
        for (let a = list.length - 1; a >= 0; a--) {
          item = list[a]
          if (keys.some(t => t === item.CLASSESDATE)) {
            list.splice(a, 1)
          } else {
            keys.push(item.CLASSESDATE)
          }
        }
        return list
      },
      // 找出重复时间下标
      removeSame(list) {
        var index = '';
        for (var i = 0; i < list.length; i++) {
          for (var j = i + 1; j < list.length; j++) {
            if (list[i].CLASSESDATE == list[j].CLASSESDATE) {
              index += i + ',' + j + ',';
            }
          }
        }
        var arr = index.split(",");
        arr = this.uniqueArr(arr);
        return arr;
      },
      // 去重
      uniqueArr(array) {
        var n = []; //一个新的临时数组
        //遍历当前数组
        for (var i = 0; i < array.length; i++) {
          //如果当前数组的第i已经保存进了临时数组，那么跳过，
          //否则把当前项push到临时数组里面
          if (n.indexOf(array[i]) == -1 && array[i] != '') n.push(array[i]);
        }
        return n;
      },
    },
  }

</script>
<style lang="scss" scoped>

</style>
